<!-- 车间管理 -->
<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot-scope="{ row }" slot="status">
        <el-tag :class="row.status ? 'successTag' : 'dangerTag'">{{ row.status ? '是' : '否' }}</el-tag>
      </template>
      <template slot="menuLeft">
        <el-button type="danger" size="small" icon="el-icon-delete" v-if="permission.workshop_delete" @click="handleDelete">删 除 </el-button>
      </template>
      <!--      <template slot="menuRight">-->
      <!--        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>-->
      <!--      </template>-->
    </avue-crud>
    <global-modal-template :visibile.sync="visibile" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </global-modal-template>
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove } from '@/api/admin/workshop';
import { mapGetters } from 'vuex';
import GlobalModalTemplate from '@/components/common-modal-template/global-modal-template.vue';
import { getDeptTree, getDeptLazyTree } from '@/api/system/dept';
import { validateContacts } from '@/mixins/validateContacts.js';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
export default {
  name: 'AdminWorkshop',
  components: {
    GlobalModalTemplate,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      visibile: false,
      pageCode: 'ADMIN_WORKSHIP',
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      form: {},
      defaults: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'calc(100vh - 360px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        labelWidth: 130,
        border: true,
        index: true,
        viewBtn: true,
        viewBtnText: '详情',
        viewTitle: '详情',
        selection: true,
        dialogClickModal: false,
        indexLabel: '序号',
        columnBtn: false,
        column: [
          {
            label: '车间编码',
            prop: 'code',
            rules: [
              {
                required: true,
                message: '请输入车间编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '车间名称',
            prop: 'name',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入车间名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '所属部门',
            prop: 'deptId',
            search: true,
            searchType: 'input',
            type: 'tree',
            multiple: false,
            hide: true,
            viewDisplay: false,
            dicData: [],
            rules: [
              {
                required: true,
                message: '请输入所属部门',
                trigger: 'blur'
              }
            ],
            props: {
              label: 'title',
              value: 'id'
            },
            nodeClick: (data, node, nodeComp) => {
              this.form.deptName = data.title;
            }
          },
          {
            label: '所属部门',
            prop: 'deptName',
            editDisplay: false,
            addDisplay: false
          },
          {
            label: '车间负责人',
            prop: 'principalName',
            type: 'search',
            disabled: true,
            // viewDisplay: false,
            // hide: true,
            appendClick: () => {
              this.openUserCommonModal({ type: 'principalName' });
            },
            rules: [
              {
                required: true,
                message: '请输入车间负责人',
                trigger: 'blur'
              }
            ]
          },
          // {
          //   label: '车间负责人',
          //   prop: 'realName',
          //   editDisplay: false
          // },
          {
            label: '联系方式',
            prop: 'contacts',
            rules: [{ validator: validateContacts, trigger: 'blur' }]
          },
          {
            label: '启用',
            prop: 'status',
            type: 'switch',
            align: 'center',
            value: 1,
            html: true,
            formatter: (val) => {
              switch (val.status) {
                case 1:
                  return `<span class="stateWords-success">启用</span>`;
                case 2:
                  return `<span class="stateWords-danger">禁用</span>`;
                default:
                  break;
              }
            },
            dataType: 'number',
            dicData: [
              {
                label: '否',
                value: 0
              },
              {
                label: '是',
                value: 1
              }
            ]
          },
          // {
          //   label: '安全生产开始日期',
          //   prop: 'lastAccident',
          //   span: 12,
          //   type: 'date',
          //   valueFormat: 'yyyy-MM-dd',
          //   format: 'yyyy-MM-dd'
          // },
          {
            label: '备注',
            prop: 'remark',
            type: 'textarea',
            minRows: 3,
            span: 24
          }
        ]
      },
      data: []
    };
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.workshop_add, false),
        viewBtn: this.vaildData(this.permission.workshop_view, false),
        delBtn: this.vaildData(this.permission.workshop_delete, false),
        editBtn: this.vaildData(this.permission.workshop_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids;
      // return ids.join(',');
    }
  },
  mounted() {
    this.$nextTick(() => {
      //搜索与表格结构分隔
      this.$structuralSplit();
    });

    // 获取部门树形数据
    let tenantId = JSON.parse(localStorage.getItem('saber-tenantId') || '{}').content;
    this.initData(tenantId);
  },
  methods: {
    initData(tenantId) {
      getDeptTree(tenantId).then((res) => {
        const column = this.findObject(this.option.column, 'deptId');
        column.dicData = res.data.data;
      });
    },
    rowSave(row, done, loading) {
      console.log('row', row);
      add(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          window.console.log(error);
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      update(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          done();
        },
        (error) => {
          loading();
          console.log(error);
        }
      );
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove([row.id]);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          console.log(this.ids, 999);
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      // this.defaults.principalName.type = ['view'].includes(type) ? 'input' : 'search';
      if (['edit', 'view'].includes(type)) {
        getDetail(this.form.id).then((res) => {
          this.form = res.data.data || this.form;
          console.log(this.form, 'this.form');
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      if (params.deptId) {
        params.deptName = params.deptId;
        delete params.deptId;
      }
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    openUserCommonModal(params) {
      let { type } = params;
      switch (type) {
        // 用户管理信息
        case 'principalName':
          this.modalName = 'principalNameModal';
          this.visibile = true;
          this.tableOption = {
            modalTitle: '选择用户管理信息（双击进行选择）',
            url: '/api/blade-system/user/page',
            isPage: true,
            rowSelectionType: 'single',
            menuWidth: 100,
            templateName: 'USER'
          };
          break;
        default:
          break;
      }
    },
    // 获取选择的模态框行数据
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'principalNameModal':
          console.log(this.form, 11999);
          this.form.principalBy = this._get(rowData, 'id', '');
          this.$set(this.form, 'principalName', this._get(rowData, 'account', ''));
          console.log(this.form, 999);
          break;
        default:
          break;
      }
    },
    // 重新加载公用表格弹窗组件
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>

<style></style>
